package likou.jindian;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/05/26 09:57
 */
public class _16_26 {
    public int calculate(String s) {
        char[] chars = s.toCharArray();
        return eval(chars, 0, chars.length);
    }

    private int eval(char[] chars, int s, int e) {
        int a = 0;
        int b = 0;
        char op = '?';
        int mark = 0;

        for (int i = s; i < e; i++) {
            if (chars[i] == ' ') {
                continue;
            } else if (chars[i] >= '0' && chars[i] <= '9') {
                if (op == '?') {
                    a = a * 10 + (chars[i] - '0');
                } else {
                    b = b * 10 + (chars[i] - '0');
                }
            } else if (op == '?' && (chars[i] == '+' || chars[i] == '-')) {
                op = chars[i];
                mark = i + 1;
            } else if (op == '?' && (chars[i] == '*' || chars[i] == '/')) {
                op = chars[i];
            } else if (op != '?' && (chars[i] == '+' || chars[i] == '-' || chars[i] == '*' || chars[i] == '/')) {
                if (op == '+') {
                    if (chars[i] == '+' || chars[i] == '-') {
                        a = a + b;
                    } else {
                        // 如果后面的那个字符为*或者/，则a就需要加上后面的部分的乘/除
                        return a + eval(chars, mark, e);
                    }
                } else if (op == '-') {
                    if (a == 0) {
                        a = -b;
                    } else {
                        if (chars[i] == '+' || chars[i] == '-') {
                            a = a - b;
                        } else {
                            return a + eval(chars, mark - 1, e);
                        }
                    }
                } else if (op == '*') {
                    a = a * b;
                } else {
                    a = a / b;
                }
                op = chars[i];
                b = 0;
                mark = i + 1;
            }
        }

        if (op == '?') {
            return a;
        } else {
            if (op == '+') {
                return a + b;
            } else if (op == '-') {
                return a - b;
            } else if (op == '*') {
                return a * b;
            } else if (op == '/') {
                return a / b;
            }
        }
        return 0;   //dummy return statement
    }
}
